﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Net.Mail;
using System.Drawing;
using System.Drawing.Imaging;
using Common;
using BusinessLogic;
using Presentation;
using BusinessObjects;

namespace DaycareSystem {
  static class Program {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main( ) {
      
     
      Application.ThreadException += new System.Threading.ThreadExceptionEventHandler( Application_UnhandledException );
      Application.EnableVisualStyles( );
      Application.SetCompatibleTextRenderingDefault( false );

      new BusinessLogic.AppBll( ).GetAppData( );

      if ( SettingsSingleton.Settings.FirstRun ) {
        Application.Run( new MainForm( SettingsSingleton.Settings.FirstRun ) );
      } else {
        User user = new UserBll( ).GetAutoLogonUser( );
        if ( user != null ) {
          SettingsSingleton.Settings.CurrentUser = user;
          Application.Run( new MainForm( ) );
        } else {
          LoginForm loginForm = new LoginForm( );
          loginForm.ShowDialog( );
          if ( loginForm.DialogResult == DialogResult.OK ) {
            if ( loginForm.LoginSucceeded ) {
              Application.Run( new MainForm( ) );
            }
          }
        }
      }
    }

    /// <summary>
    /// Handles the UnhandledException event of the Application control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Threading.ThreadExceptionEventArgs"/> instance containing the event data.</param>
    static void Application_UnhandledException( object sender, System.Threading.ThreadExceptionEventArgs e ) {

      try {
        if ( MailHelper.InternetConnectionAvailable() ) {

        string messageMediaType = "text/html";

        MailMessage message = new MailMessage( );
        message.To.Add( SettingsSingleton.Settings.SystemEmail );
        message.From = new MailAddress( SettingsSingleton.Settings.CurrentUser.Email );
        message.Priority = MailPriority.High;
        message.Subject = "Unhandled exception error";

        string body = CreateExceptionText( e.Exception );

        AlternateView htmlContent = AlternateView.CreateAlternateViewFromString( body, null, messageMediaType );
        TakeScreenShot( );

        LinkedResource screenshot = new LinkedResource( "screenshot.png" );
        screenshot.ContentId = "SCREENSHOT";
        htmlContent.LinkedResources.Add( screenshot );
        message.AlternateViews.Add( htmlContent );

        SmtpClient smtp = new SmtpClient( SettingsSingleton.Settings.SmtpServerName,SettingsSingleton.Settings.SmtpPort );
        smtp.Credentials = new System.Net.NetworkCredential( SettingsSingleton.Settings.SmtpUserName, SettingsSingleton.Settings.SmtpPassword );
        smtp.EnableSsl = true;
        smtp.Send( message );

        MessageBox.Show(
          "Er is een onverwachte fout opgetreden. De fout is doorgestuurd naar tech support.\nApplicatie wordt nu afgesloten.",
          "Onverwachte fout", MessageBoxButtons.OK, MessageBoxIcon.Error );
        } else {
          MessageBox.Show(
            "Er is een onverwachte fout opgetreden. De fout kon niet doorgestuurd worden naar tech support.\nApplicatie wordt nu afgesloten.",
            "Onverwachte fout", MessageBoxButtons.OK, MessageBoxIcon.Error );
        }
      } finally {
        Application.Exit( );
      }

    }

    /// <summary>
    /// Takes a screen shot.
    /// </summary>
    private static void TakeScreenShot( ) {
      Form mainForm = Application.OpenForms[ "MainForm" ];
      Rectangle bounds = mainForm.Bounds;
      using ( Bitmap screenshot = new Bitmap( bounds.Width, bounds.Height ) ) {
        using ( Graphics graphics = Graphics.FromImage( screenshot ) ) {
          graphics.CopyFromScreen( mainForm.Location, Point.Empty, bounds.Size );
        }
        screenshot.Save( "screenshot.png", ImageFormat.Png );
      }
    }

    /// <summary>
    /// Creates the exception text.
    /// </summary>
    /// <param name="ex">The ex.</param>
    /// <returns></returns>
    private static string CreateExceptionText( Exception ex ) {
      return string.Format( @"
                          <p>
                            <pre>
                          ------------------------------------------------
                          An error occurred in {0}
                          ------------------------------------------------
                          {1}
                            </pre>
                              <img src='cid:SCREENSHOT' />
                          </p>", Application.ProductName, FormatException( ex ) );
    }

    /// <summary>
    /// Formats the exception.
    /// </summary>
    /// <param name="ex">The ex.</param>
    /// <returns></returns>
    private static string FormatException( Exception ex ) {
      if ( ex == null ) {
        return string.Empty;
      } else {
        return string.Format( @"<pre>{0}</pre>
            ------------------------------------------------
            {1}", ex.ToString( ), FormatException( ex.InnerException ) );
      }
    }


  }
}
